package com.eightbears.beboy.ui.merchant.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.InputMethodUtils;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.builder.PostFormBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.FileCallBack;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.image.circle.ClipImageActivity;
import com.eightbears.beboy.base.view.picker.DatePicker;
import com.eightbears.beboy.base.view.popupwindow.BottomSelectionPopup;
import com.eightbears.beboy.entity.ShopSetMealEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CAHCE_IMAGE_FILE;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_ADD_SHOPMEAL;
import static com.eightbears.beboy.base.util.CommonAPI.URL_ORDER_DETAIL;
import static com.eightbears.beboy.ui.merchant.activity.ShopSetMealActivity.PARAMS_SET_MEAL_ENTITY;

public class ShopSetMealEditActivity extends BaseActivity {

    private static final String PARAMS_START_TIME = "startTime";
    private static final String PARAMS_END_TIME = "endTime";
    public static final String EVENT_EDIT_SET_MEAL_SUCCESS = "editSetMealSuccess";

    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_icon)
    ImageView iv_icon;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.et_dis_price)
    EditText et_dis_price;
    @BindView(R.id.et_price)
    EditText et_price;
    @BindView(R.id.et_num)
    EditText et_num;
    @BindView(R.id.et_content)
    EditText et_content;
    @BindView(R.id.tv_start_time)
    TextView tv_start_time;
    @BindView(R.id.tv_end_time)
    TextView tv_end_time;
    @BindView(R.id.view_loading)
    View view_loading;
    @BindView(R.id.tv_loading_text)
    TextView tv_loading_text;

    private String setMealTitle, disPrice, price, num,
            setMealContent, startTime, endTime;
    private String selTimeType = "";

    // 头像
    private static final int REQUEST_CAPTURE = 100;        //请求相机
    private static final int REQUEST_PICK = 101;          //请求相册
    private static final int REQUEST_CROP_PHOTO = 102;    //请求截图
    private File tempFile;                                //调用照相机返回图片文件
    private String cropImagePath;                         // 剪裁路径

    private BottomSelectionPopup bottomSelectionPopup;
    private UserEntity.Shop shop;
    private ShopSetMealEntity.SetMeal shopSetMealEntity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_set_meal_edit);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tv_title.setText(R.string.text_edit_set_meal);
        tv_loading_text.setText(getString(R.string.text_submit_data_wait));
        if (getExtras() != null)
            shopSetMealEntity = (ShopSetMealEntity.SetMeal) getExtras().get(PARAMS_SET_MEAL_ENTITY);
    }

    @Override
    protected void initData() {
        shop = SPUtil.getUser().getData().getShops().get(0);
        if (shopSetMealEntity != null) {
            downShopImage();
        }
    }


    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    private void initInputInfo() {
        et_name.setText(shopSetMealEntity.getTitle());
        et_dis_price.setText(shopSetMealEntity.getDiscount_price());
        et_price.setText(shopSetMealEntity.getPrice());
        et_num.setText(shopSetMealEntity.getRec_num());
        tv_start_time.setText(CommonUtils.TimeStamp2Date(shopSetMealEntity.getStart_at(), "yyyy-MM-dd"));
        tv_end_time.setText(CommonUtils.TimeStamp2Date(shopSetMealEntity.getEnd_at(), "yyyy-MM-dd"));
        et_content.setText(shopSetMealEntity.getContent());
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }


    @OnClick(R.id.rl_setting_head)
    void setIcon() {
        showImageDialog();
    }

    @OnClick(R.id.tv_commit)
    void editSetMeal() {
        if (checkInput()) {
            view_loading.setVisibility(View.VISIBLE);
            updateData();
        }
    }

    @OnClick(R.id.tv_start_time)
    void starTime() {
        selTimeType = PARAMS_START_TIME;
        showTimePick();
    }

    @OnClick(R.id.tv_end_time)
    void endTime() {
        selTimeType = PARAMS_END_TIME;
        showTimePick();
    }

    private void downShopImage() {
        String fileName = System.currentTimeMillis() + "_";
        OkHttpUtils.get().url(shopSetMealEntity.getCover())
                .build().execute(new FileCallBack(CAHCE_IMAGE_FILE, fileName + ".png") {
            @Override
            public void onResponse(File response) {
                CommonUtils.loadImageView(ShopSetMealEditActivity.this, response, R.mipmap.icon_default_shop, iv_icon);
                cropImagePath = response.getPath();
                initInputInfo();
            }

            @Override
            public void inProgress(float progress) {

            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
            }

        });

    }

    private void showTimePick() {
        DatePicker picker = new DatePicker(this);
        picker.setUseWeight(true);
        picker.setCanceledOnTouchOutside(true);
        picker.setRangeStart(CommonUtils.getDate()[0], CommonUtils.getDate()[1], CommonUtils.getDate()[2]);
        picker.setRangeEnd(2100, 1, 1);
        picker.setSelectedItem(CommonUtils.getDate()[0], CommonUtils.getDate()[1], CommonUtils.getDate()[2]);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                switch (selTimeType) {
                    case PARAMS_START_TIME:
                        startTime = year + "-" + month + "-" + day;
                        tv_start_time.setText(startTime);
                        break;
                    case PARAMS_END_TIME:
                        startTime = year + "-" + month + "-" + day;
                        tv_end_time.setText(startTime);
                        break;
                }
            }
        });
        picker.show();
    }

    private boolean checkInput() {

        setMealTitle = et_name.getText().toString().trim();
        disPrice = et_dis_price.getText().toString().trim();
        price = et_price.getText().toString().trim();
        num = et_num.getText().toString().trim();
        setMealContent = et_content.getText().toString().trim();
        startTime = tv_start_time.getText().toString().trim();
        endTime = tv_end_time.getText().toString().trim();


        if (TextUtils.isEmpty(cropImagePath)) {
            ShowToast.showShortToast(getString(R.string.alert_sel_set_meal_icon));
            return false;
        }

        if (TextUtils.isEmpty(setMealTitle)) {
            ShowToast.showShortToast(getString(R.string.hint_input_set_meal_name));
            return false;
        }

        if (TextUtils.isEmpty(disPrice)) {
            ShowToast.showShortToast(getString(R.string.hint_input_set_meal_dis_price));
            return false;
        }

        if (Double.parseDouble(disPrice) <= 0) {
            ShowToast.showShortToast(getString(R.string.text_not_zero));
        }

        if (TextUtils.isEmpty(price)) {
            ShowToast.showShortToast(getString(R.string.hint_input_set_meal_price));
            return false;
        }

        if (Double.parseDouble(price) <= 0) {
            ShowToast.showShortToast(getString(R.string.text_not_zero));
        }

        if(Integer.parseInt(price) < Integer.parseInt(disPrice)) {
            ShowToast.showShortToast(getString(R.string.alert_price_dis_error));
        }
        
        if (TextUtils.isEmpty(num)) {
            ShowToast.showShortToast(getString(R.string.hint_input_set_meal_num));
            return false;
        }

        if (Integer.parseInt(num) <= 0) {
            ShowToast.showShortToast(getString(R.string.text_not_zero));
        }

        if (TextUtils.isEmpty(startTime)) {
            ShowToast.showShortToast(getString(R.string.alert_sel_start_time));
            return false;
        }

        if (TextUtils.isEmpty(endTime)) {
            ShowToast.showShortToast(getString(R.string.text_sel_end_time));
            return false;
        }

        if(startTime.equals(endTime)) {
            ShowToast.showShortToast(getString(R.string.alert_start_equals_end));
            return false;
        }

        startTime = CommonUtils.Date2TimeStamp(startTime, "yyyy-MM-dd");
        endTime = CommonUtils.Date2TimeStamp(endTime, "yyyy-MM-dd");
        if (Integer.parseInt(startTime) > Integer.parseInt(endTime)) {
            ShowToast.showShortToast(getString(R.string.text_start_end_errpr));
        }

        if (TextUtils.isEmpty(setMealContent)) {
            ShowToast.showShortToast(getString(R.string.hint_input_set_meal_content));
            return false;
        }

        return true;
    }

    private void showImageDialog() {

        if (bottomSelectionPopup == null) {
            bottomSelectionPopup = new BottomSelectionPopup(this);
            bottomSelectionPopup.setTxCancel(getResources().getString(R.string.btn_cancel));
            bottomSelectionPopup.setTx_1Text(getResources().getString(R.string.text_select_image));
            bottomSelectionPopup.setTx_2Text(getResources().getString(R.string.text_select_capture));
            bottomSelectionPopup.setOnClickItemListener(new BottomSelectionPopup.OnClicktemListener() {
                @Override
                public void onClickItem(View v) {
                    switch (v.getId()) {
                        case R.id.ll_1:
                            selectPicture();
                            break;
                        case R.id.ll_2:
                            getCapture();
                            break;
                    }
                }
            });
        }
        bottomSelectionPopup.showPopupWindow();
    }

    private void selectPicture() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
    }

    private void getCapture() {
        //创建拍照存储的图片文件
        tempFile = new File(checkDirPath(CommonAPI.CACHE_HEAD_FILE), System.currentTimeMillis() + ".jpg");
        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    /**
     * 检查文件是否存在
     */
    private static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }

    /**
     * 根据Uri返回文件绝对路径, file:///开头的 和 content://开头的情况
     */
    public static String getRealFilePathFromUri(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 打开截图界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this, ClipImageActivity.class);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_CROP_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CAPTURE:
                if (resultCode == RESULT_OK) {
                    gotoClipActivity(Uri.fromFile(tempFile));
                }
                break;
            case REQUEST_PICK:
                if (null != data) {
                    Uri pickUri = data.getData();
                    gotoClipActivity(pickUri);
                }

                break;
            case REQUEST_CROP_PHOTO:
                if (resultCode == RESULT_OK) {
                    Uri cropUri = data.getData();
                    if (cropUri == null) {
                        return;
                    }
                    cropImagePath = getRealFilePathFromUri(getApplicationContext(), cropUri);
                    CommonUtils.loadImageView(this, new File(cropImagePath), R.mipmap.icon_default_shop, iv_icon);
                }
                break;
        }

    }


    private void updateData() {

        String url;
        if (shopSetMealEntity == null)
            url = URL_ADD_SHOPMEAL + shop.getShop_id() + "/" + "coupon";
        else
            url = URL_ORDER_DETAIL + shopSetMealEntity.getId();

        PostFormBuilder builderPost = OkHttpUtils.post();
        builderPost.url(url);
        builderPost.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        builderPost.addFile("cover", "cover_" + System.currentTimeMillis() + ".png", new File(cropImagePath));
        builderPost.addParams("id", shop.getShop_id());
        builderPost.addParams("title", setMealTitle);
        builderPost.addParams("content", setMealContent);
        builderPost.addParams("rec_num", num);
        builderPost.addParams("price", price);
        builderPost.addParams("discount_price", disPrice);
        builderPost.addParams("start_at", startTime);
        builderPost.addParams("end_at", endTime);
        builderPost.build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                view_loading.setVisibility(View.GONE);
                ShowToast.showShortToast(R.string.alert_submit_success);
                EventBus.getDefault().post(EVENT_EDIT_SET_MEAL_SUCCESS);
                finish();
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                view_loading.setVisibility(View.GONE);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShopSetMealEditActivity.this, status_error);
            }
        });

    }

    @Override
    public void finish() {
        super.finish();
        InputMethodUtils.closeInputMethod(this, et_name);
    }
}
